package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.exception.TokenException;
import com.itheima.pojo.User;
import com.itheima.thread.UserTokenThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {


//    @Autowired
//    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    //拦截器的处理

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("AuthorizationUser");//请求头
        //hasText:是否存在内容
        if (!StringUtils.hasText(token)){
            throw new TokenException();
        }

        //因为知道内容是string，所以可以直接使用string
        String user = (String) redisTemplate.opsForValue().get("user_token" + token);
//        System.out.println("================================");
//        log.info("{}",employee);
//        System.out.println("================================");




        //判断是否为空   hasText（是否有内容）
        if (!StringUtils.hasText(user)){
            //不存在则抛异常
            throw new TokenException();
        }


                      //json字符串转换成对象  (见EmployeeServiceImpl  46行)
        User use = JSON.parseObject(user, User.class);


        if (use==null){
            throw new TokenException();
        }


        UserTokenThreadUtils.setThreadLocal(use);


        //30分钟内无操作将删除token   有操作的话刷新token（因为在拦截器内，有操作就会经过拦截器）
        redisTemplate.opsForValue().set("user_token" + token,user,30, TimeUnit.MINUTES);
        return true;
    }
}
